/**
 * 十六进制颜色值转rgb数组
 * @param color 十六进制颜色值
 * @returns [R, G, B]
 */
export const Hex2RGB = (color: string) => {
    const hex = color.replace("#", "");
    if (hex.length === 3) {
        return hex.split("").map((_) => parseInt(_, 16));
    } else if (hex.length === 6) {
        return Array(3)
            .fill(0)
            .map((_, index) => parseInt(hex.slice(index * 2, index * 2 + 2), 16));
    } else {
        throw new Error(`无法解析传入的Hex颜色${color}`);
    }
};

/**
 * RGB数组转十六进制颜色值
 * @param r 红色通道值
 * @param g 绿色通道值
 * @param b 蓝色通道值
 * @returns 十六进制颜色值
 */
export const RGB2Hex = (...rest: number[]) => {
    const [r, g, b] = rest;
    const arr = [r.toString(16), g.toString(16), b.toString(16)];
    const hex = arr.map((item) => (item.length === 1 ? `0${item}` : item)).join("");

    return `#${hex}`;
};

/**
 * 加深颜色
 * @param {string} color 十六进制颜色值
 * @param {number} ratio 加深比率
 * @returns 加深后的颜色值
 */
export const dark = (color: string, ratio: number) => {
    const rgb = Hex2RGB(color).map((item) => Math.floor(item * (1 - ratio)));
    return RGB2Hex(...rgb);
};

/**
 * 减淡颜色
 * @param {string} color 十六进制颜色值
 * @param {number} ratio 减淡比率
 * @returns 减淡后的颜色值
 */
export const light = (color: string, ratio: number) => {
    const rgb = Hex2RGB(color).map((item) => Math.floor(item + (255 - item) * ratio));
    return RGB2Hex(...rgb);
};

export default {
    dark,
    light,
    Hex2RGB,
    RGB2Hex,
};
